package com.hdumooc.test.dbutils;

import com.hdumooc.utils.DruidUtils;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;

public class DBUtilsDemo02 {

    @Test
    public void testInsert() throws SQLException {
        // 1.创建 QueryRunner 手动模式创建
        QueryRunner queryRunner = new QueryRunner();
        // 2.编写 占位符方式 SQL
        String sql = "INSERT INTO employee VALUES(?, ?, ?, ?, ?, ?)";
        // 3.设置占位符的参数
        Object[] param = { null, "张百万", 20, "女", 10000, "1990-12-26" };
        // 4.执行 update 方法
        Connection connection = DruidUtils.getConnection();
        int i = queryRunner.update(connection, sql, param);
        System.out.println(i);
        // 5.释放资源
        DbUtils.closeQuietly(connection);
    }

    /**
     * 修改姓名为张百万的员工工资
     */
    @Test
    public void testUpdate() throws SQLException {
        // 1.自动模式创建 QueryRunner 对象，传入 dataSource
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        // 2.编写 SQL
        String sql = "UPDATE employee SET salary = ? WHERE name = ?";
        // 3.设置占位符参数
        Object[] params = { 0, "张百万" };
        // 4.执行 update，不需要传入连接对象
        queryRunner.update(sql, params);
    }

    /**
     * 删除 id 为 1的数据
     */
    @Test
    public void testDelete() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "DELETE FROM employee WHERE id = ?";
        // 只有一个参数，不需要创建数组
        queryRunner.update(sql, 1);
    }
}
